package cn.edu.pzhu.javaweb.service.imp;

import cn.edu.pzhu.javaweb.dao.imp.UserDaoimp;
import cn.edu.pzhu.javaweb.dao.imp.UserinfoDaoimp;
import cn.edu.pzhu.javaweb.pojo.Result;
import cn.edu.pzhu.javaweb.pojo.User;
import cn.edu.pzhu.javaweb.pojo.Userinfo;
import cn.edu.pzhu.javaweb.dao.UserinfoDao;

import java.sql.Connection;
import java.sql.SQLException;

import cn.edu.pzhu.javaweb.dao.UserDao;
import cn.edu.pzhu.javaweb.service.UserService;
import cn.edu.pzhu.javaweb.util.DBUtil;

public class UserServiceImp implements UserService{
	private UserDao userdao = new  UserDaoimp();
	private UserinfoDao userinfoDao = new UserinfoDaoimp();
	public UserServiceImp() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public Result<String> regist(User user, Userinfo userinfo) {
		if (user == null || user.getUsername() == null || user.getPassword() == null
	            || user.getUsername().isEmpty() || user.getPassword().isEmpty()) {
	        return Result.fail("数据异常！");
	    }
	    if (userinfo == null || userinfo.getUsername() == null || userinfo.getEmail() == null
	            || userinfo.getType().isEmpty()) {
	        return Result.fail("数据异常！");
	    }
	    User dbuser = userdao.selectById(user.getUsername());
	    if (dbuser != null) {
	        return Result.fail("用户已经被注册！");
	    }
	    Connection con = null;
	    try {
	        con = DBUtil.getConnection();
	        con.setAutoCommit(false); // 关闭自动提交
	        int i = userdao.insert(user, con);
	        int j = userinfoDao.insert(userinfo, con);
	        
	        if (i > 0 && j > 0) {
	            con.commit();
	            return Result.success();
	        } else {
	            con.rollback();
	        }
	    } catch (SQLException e) {
	        e.printStackTrace();
	    } finally {
	        DBUtil.close(con);
	    }
	    return Result.fail("注册失败！");
	}

	@Override
	public Result<String> login(User user) {
	    try {
	        if (user == null || user.getUsername() == null || user.getPassword() == null
	                || user.getUsername().isEmpty() || user.getPassword().isEmpty()) {
	            return Result.fail("数据异常");
	        }
	        User dbuser = userdao.selectById(user.getUsername());
	        if (dbuser == null) {
	            return Result.fail("用户不存在");
	        }
	        if (dbuser.getStatus() == 0) {
	            return Result.fail("账户已被注销");
	        }
	        if (!dbuser.getPassword().equals(user.getPassword())) {
	            return Result.fail("密码错误");
	        }
	        return Result.success();
	    } catch (Exception e) {
	        e.printStackTrace();
	        return Result.fail("登录过程中出现异常");
	    }
	}

	@Override
	public Result<Userinfo> getPersonalInfo(String username) {
		if (username == null || username.isEmpty()) {
			return Result.fail("数据异常");
		}
		Userinfo userinfo = userinfoDao.selectById(username);
		return Result.success(userinfo);
	}

	@Override
	public Result<String> UpdatePersonalInfo(Userinfo userinfo) {
		if (userinfo == null || userinfo.getUsername() == null || userinfo.getUsername().isEmpty()) {
	        return Result.fail("用户信息不完整");
	    }
	    
	    // 调用Dao层更新用户信息
	    int updateCount = userinfoDao.update(userinfo);
	    if (updateCount > 0) {
	        return Result.success("个人信息修改成功");
	    } else {
	        return Result.fail("修改失败，请检查信息是否正确");
	    }
	}

	@Override
	public Result<String> UpdatePassword(String username, String oldPassword, String newPassword) {
		if (username == null || username.isEmpty() || oldPassword == null || 
				oldPassword.isEmpty() || newPassword == null || newPassword.isEmpty()) {
			return Result.fail("用户信息不完整");
		}
		// 先查询用户是否存在
		User dbUser = userdao.selectById(username);
		if (dbUser == null) {
			return Result.fail("用户不存在");
		}
		// 验证旧密码是否正确
		if (!dbUser.getPassword().equals(oldPassword)) {
			return Result.fail("旧密码错误");
		}
		// 创建更新对象，只设置新密码，不修改状态
		User updateUser = new User(username, newPassword, null);
		// 更新密码
		int result = userdao.update(updateUser);
		if (result > 0) {
			return Result.success();
		} else {
			return Result.fail("密码修改失败");
		}
	}

	@Override
public Result<String> destroyAccount(String username, String password) {
	if (username == null || username.isEmpty() || password == null || password.isEmpty()) {
		return Result.fail("用户名或密码不能为空");
	}
	// 查询用户是否存在
	User dbUser = userdao.selectById(username);
	if (dbUser == null) {
		return Result.fail("用户不存在");
	}
	// 验证密码
	if (!dbUser.getPassword().equals(password)) {
		return Result.fail("密码错误");
	}
	
	// 使用事务确保数据一致性
	Connection con = null;
	try {
		con = DBUtil.getConnection();
		con.setAutoCommit(false); // 关闭自动提交
		
		// 1. 删除用户详细信息
		userinfoDao.deleteById(username);
		// 2. 删除用户基本信息
		int result = userdao.deleteById(username);
		
		if (result > 0) {
			con.commit(); // 提交事务
			return Result.success();
		} else {
			con.rollback(); // 回滚事务
			return Result.fail("账户注销失败");
		}
	} catch (SQLException e) {
		e.printStackTrace();
		try {
			if (con != null) {
				con.rollback(); // 发生异常时回滚事务
			}
		} catch (SQLException ex) {
			ex.printStackTrace();
		}
		return Result.fail("账户注销过程中发生异常");
	} finally {
		DBUtil.close(con);
	}
	}

	@Override
	public boolean checkUsername(String username) {
		if(username==null||username.isEmpty()){
			return false;
		}
		User dbuser = userdao.selectById(username);
		if(dbuser!=null) {
			return true;
		}else{
			return false;
		}
}
	}
